package jgl.vajra.kingkong.part.vehicle.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.CommonAddressBean;
import jgl.vajra.kingkong.bean.PeripheralPoiBean;
import jgl.vajra.kingkong.databinding.ActivityEditAddressBinding;
import jgl.vajra.kingkong.event.MapPointEvent;
import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.part.vehicle.contract.EditAddressContract;
import jgl.vajra.kingkong.part.vehicle.viewModel.EditAddressViewModel;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.permissions.PermissionListener;
import jgl.vajra.kingkong.widget.permissions.PermissionsUtil;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

@CreateViewModel(EditAddressViewModel.class)
public class EditAddressActivity extends BaseMVVMActivity<EditAddressViewModel, ActivityEditAddressBinding> implements EditAddressContract.View {

    private PeripheralPoiBean addressBean;
    private String authorization;
    private CommonAddressBean itemData;

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_address;
    }

    @Override
    public void initView() {
        super.initView();
        itemData = getIntent().getParcelableExtra("itemData");
        if (itemData != null && !TextUtils.isEmpty(itemData.address)) {
            mBinding.tvAddress.setText(itemData.address);
            mBinding.tvAddress.setTextColor(UIUtils.getColor(R.color.color_333333));
            mBinding.etHouseNumber.setText(itemData.houseNumber);
            mBinding.etName.setText(itemData.contactName);

            String decrypt = AEACCoder.decrypt(itemData.contactPhone);
            mBinding.etPhone.setText(decrypt);
            addressBean = new PeripheralPoiBean(itemData.address, itemData.houseNumber, Double.parseDouble(itemData.latitude), Double.parseDouble(itemData.longitude), itemData.city);
        }

        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;
        mBinding.setView(this);
    }

    //地图选点
    @Override
    public void onMapPoint() {
        IntentManager.toMapPointActivity(this);
    }

    //确定
    @Override
    public void onDetermine() {

        if (TextUtils.isEmpty(addressBean.detailedAddress)) {
            ToastUtils.showShort("请输入地址");
            return;
        }

        String houseNumber = mBinding.etHouseNumber.getText().toString().trim();
        String name = mBinding.etName.getText().toString().trim();
        String phone = mBinding.etPhone.getText().toString().trim();

        Map<String, Object> map = new HashMap<>();
        map.put("address", addressBean.detailedAddress);
        map.put("houseNumber", houseNumber);
        map.put("city", addressBean.city);
        map.put("contactName", name);
        if (!TextUtils.isEmpty(phone)) {
            phone = AEACCoder.encrypt(phone);
        }
        map.put("contactPhone", phone);
        map.put("longitude", addressBean.longitude);
        map.put("latitude", addressBean.latitude);

        //有id修改地址
        if (itemData != null && itemData.id != 0) {
            map.put("id", itemData.id);
        }

        mViewModel.addAddressData(map, authorization);


    }

    //通讯录
    @Override
    public void onMailList() {
        String[] permissions = {
                Manifest.permission.READ_CONTACTS,

        };
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );
    }

    @Override
    public void returnAddAddress(String msg) {
        ToastUtils.showShort(msg);
        finish();
    }

    /* * 跳转联系人列表的回调函数 * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = getPhoneContacts(uri);
            mBinding.etName.setText(contacts != null ? contacts[0] : "");
            String phone = contacts != null ? contacts[1] : "";
            if (!TextUtils.isEmpty(phone)) {
                phone =phone.replace(" ", "");
            }
            mBinding.etPhone.setText(phone);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone.close();
            }
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMapPointEvent(MapPointEvent event) {
        addressBean = event.bean;

        mBinding.tvAddress.setText(addressBean.detailedAddress);
        mBinding.tvAddress.setTextColor(UIUtils.getColor(R.color.color_333333));
    }
}
